import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_demo/core/cu_config/cu_err_config.dart';
import 'package:flutter_demo/models/back_model/back_model.dart';

class DioConfig {
  static const String baseUrl = "https://prd.ruyigx.com";

  static Dio get dio {
    final Dio dio = Dio();

    /// 添加拦截器
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          final token = "";
          options.headers['token'] = token;
          options.headers['Content-Type'] = 'application/json';
          handler.next(options);
        },
      ),
    );
    // 2. 响应拦截器：统一解析 BackModel + 判断 Code
    dio.interceptors.add(
      InterceptorsWrapper(
        onResponse: (response, handler) async {
          try {
            // 1. 统一解析 BackModel（和你之前的 _parseData 逻辑一样）
            Map<String, dynamic> responseData;
            if (response.data is String) {
              responseData = json.decode(response.data);
            } else if (response.data is Map<String, dynamic>) {
              responseData = Map.from(response.data);
            } else {
              throw Exception('无效的响应格式');
            }
            BackModel backModel = BackModel.fromJson(responseData);

            // 2. 统一判断 Code（处理错误、token 过期）
            if (backModel.code != CuErrorConfig.success) {
              // 处理 token 过期（和你之前的逻辑一样）
              if ([
                CuErrorConfig.err_1000,
                CuErrorConfig.err10001,
                CuErrorConfig.err_502,
              ].contains(backModel.code)) {
                // 退出
                // await UserInfo.instance.loginOut();
              }

              print("接口错误：${backModel.msg}，Code：${backModel.code}");

              // 把错误抛出去，让调用方可以 catch
              handler.reject(
                DioException(
                  requestOptions: response.requestOptions,
                  message: backModel.msg,
                  response: response,
                ),
              );
              return;
            }

            // 3. 解析成功：把 BackModel 传给 Retrofit
            response.data = backModel;
            handler.next(response);
          } catch (e) {
            // 格式化失败：统一返回错误
            handler.reject(
              DioException(
                requestOptions: response.requestOptions,
                message: "返回数据格式化失败：$e",
                response: response,
              ),
            );
          }
        },
        // 3. 网络异常拦截（替代你 catch 里的 500 错误）
        onError: (DioException e, handler) {
          String errorMsg = "网络错误，稍后再试：${e.message}";
          print(errorMsg);
          handler.next(e); // 继续抛出错误，方便调用方处理
        },
      ),
    );

    dio.interceptors.add(
      LogInterceptor(request: true, responseBody: true, error: true),
    );
    return dio;
  }
}
